/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ssm.changeunit;

import com.ssm.changeunit.persistance.BranchDAO;
import com.ssm.changeunit.persistance.BranchDTO;
import com.ssm.changeunit.persistance.PersistanceException;

/**
 *
 * @author 시리우스
 */
public class Branch extends AbstractProduct {
    private String branchName;
    private BranchDAO branchDAO;
    
    /**
     * 생성자
     * @param branchName
     */
    public Branch(String branchName) {
        this.branchName = branchName;
        this.branchDAO = new BranchDAO();
    }
    
    /**
     * Branch 이름을 가져옴
     * @return
     */
    public String getBranchName() {
        return branchName;
    }

    /**
     * Branch가 현재 가리키는 ChangeUnit을 가져옴
     * @return
     */
    public ChangeUnit getCurrentChangeUnit() throws PersistanceException {
        try {
            BranchDTO branchDTO = branchDAO.find(branchName);

            // Unknown일 경우 null을 리턴
            if(branchDTO == null)
                return null;
            
            return new ChangeUnitFactory().createProduct(branchDTO.getChangeUnitId());
        }
        catch(CreateException ex) {
            throw new PersistanceException(ex);
        }
    }
    
    /**
     * Branch가 현재 가리키는 ChangeUnit을 변경
     * @param chnageUnit
     * @throws com.ssm.changeunit.persistance.PersistanceException
     */
    public void setCurrentChangeUnit(ChangeUnit changeUnit) throws PersistanceException {
        BranchDTO branchDTO = branchDAO.find(branchName);
        
        branchDTO.setChangeUnitId(changeUnit.getChangeUnitId());
        
        branchDAO.update(branchDTO);
    }
    
    /**
     * Branch가 시작된 지점의 ChangeUnit을 가져옴
     * @return
     */
    public ChangeUnit getOriginChangeUnit() throws PersistanceException { 
        try {
            BranchDTO branchDTO = branchDAO.find(branchName);

            return new ChangeUnitFactory().createProduct(branchDTO.getOriginChangeUnitId());
        }
        catch(CreateException ex) {
            throw new PersistanceException(ex);
        }
    }
    
    /**
     * Branch가 시작된 지점의 ChangeUnit을 변경
     * @param changeUnit
     */
    public void setOriginChangeUnit(ChangeUnit changeUnit) throws PersistanceException {
        BranchDTO branchDTO = branchDAO.find(branchName);
        
        branchDTO.setOriginChangeUnitId(changeUnit.getChangeUnitId());
        
        branchDAO.update(branchDTO);
    }
}
